import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Text,
  Image,
  TextInput,
  SafeAreaView,
  NativeModules
} from 'react-native';
import {
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp,
  isAndroid
} from '@/styles';
import { Button, _, msg } from '@/common';
import { getGoodsCarInfo, confirmOrder, submitOrder } from '@/api/truck';
import { loginAlert, checkMobile } from '@/common/util';
import user from '@/api/user';

const { Submit } = Button;

/*
 * @Author: luoyunhai
 * @Date: 2020-08-18 10:00:00
 * @LastEditors: kanglang
 * @LastEditTime: 2020-09-22 14:30:05
 * @Description: 联系我们
 */
export default class ContactUs extends Component {
  static navigationOptions = ({ navigation }) => {
    return {
      title: navigation.getParam('otherParam') ? `${navigation.getParam('otherParam')}专区` : ''

    };
  };

  constructor(props) {
    super(props);
    this.state = {
      name: '',
      tel: '',
      goodsId: '',
      carDetail: '',
      userInfo: [],
      isDisable: false, // 防止多次提交
    };
  }

  componentDidMount() {
    this.init();
  }

  getUserInfo() {
    user.getUserInfo().then((res) => {
      if (res.success) {
        this.setState({
          userInfo: res.data,
          name: res.data.name,
          tel: res.data.wholeMobile
        });
      }
    });
  }

  getGoodsCarInfo() {
    const parame = {
      goodsId: this.state.goodsId
    };
    getGoodsCarInfo(parame).then(res => {
      if (res.success) {
        this.setState({
          carDetail: res.data
        });
      }
    });
  }

  confirmOrder() {
    const parame = {
      orderType: '6', // 4S下单预约
      truckData: {
        goodsId: this.state.goodsId
      }
    };
    this.setState({ isDisable: true });

    confirmOrder(parame).then(res => {
      this.setState({ isDisable: false });

      if (res.success) {
        this.submitOrder();
      } else {
        if (res.msg == '登录信息失效') {
          loginAlert();
          return;
        }
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  submitOrder() {
    const { goodsId, name, tel } = this.state;
    const parame = {
      orderType: '6',
      integral: '0',
      addressId: '',
      truckData: {
        goodsId: goodsId,
        name: name, // 名字
        mobile: tel // 电话
      }
    };
    this.setState({ isDisable: true });

    submitOrder(parame).then(res => {
      this.setState({ isDisable: false });

      if (res.success) {
        this.setState({
          name: '',
          tel: ''
        });
        NativeModules.WindowModule.showWindow(
          {
            content: '您的信息已提交成功，工作人员会尽快与您联系',
            title: '温馨提示',
            rightStr: '好的',
            onlyRightBtn: '1'
          },
          (e) => {
            if (e == 1) {
              msg.emit('router: back');
            }
          },
        );
      } else {
        if (res.msg == '登录信息失效') {
          loginAlert();
          return;
        }
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  handlesubmit() {
    const { tel, name } = this.state;
    if (!name) {
      msg.emit('app:tip', { text: '请输入姓名' });
      return;
    }

    if (!tel) {
      msg.emit('app:tip', { text: '请输入手机号' });
      return;
    }

    if (!checkMobile(tel)) {
      msg.emit('app:tip', { text: '请输入正确的手机号' });
      return;
    }

    this.confirmOrder();
  }

  formatePrice(number) {
    if (number) {
      return (number / 10000).toFixed(2);
    }
  }

  render() {
    const { carDetail, name, tel, userInfo, isDisable } = this.state;

    return (
      <SafeAreaView style={styles.wrap}>

        <View style={styles.carWrap}>
          <View style={styles.itemWrap}>
            <View>
              <Image
                style={styles.itemImg}
                source={{ uri: carDetail.picFileId }}
              />
            </View>
            <View style={styles.itemRight}>
              <Text style={styles.itemTitle} numberOfLines={1}>{carDetail.name}</Text>
              <Text style={styles.itemParme} numberOfLines={1}>{carDetail.details}</Text>
              <Text>
                <Text style={styles.priceTitle}>参考价：</Text>
                <Text style={styles.price}>
                  {' '}
                  ¥
                  { carDetail && this.formatePrice(carDetail.originalPrice) }
                  万
                </Text>
              </Text>
            </View>
          </View>
        </View>

        <View style={styles.formWrap}>
          <View><Text style={styles.formTitle}>联系方式</Text></View>
          <View style={styles.inpWrap}>
            <Text style={styles.mustTip}>*</Text>
            <TextInput
              style={[styles.inp, userInfo.name && styles.grayStyle]}
              placeholder='请填写您的姓名'
              value={name}
              maxLength={10}
              editable={!userInfo.name}
              onChangeText={(text) => {
                this.setState({ name: text });
              }}
            />
          </View>
          <View style={styles.inpWrap}>
            <Text style={styles.mustTip}>*</Text>
            <TextInput
              keyboardType={
                isAndroid
                  ? 'numeric'
                  : 'decimal-pad'
              }
              maxLength={11}
              style={[styles.inp, userInfo.wholeMobile && styles.grayStyle]}
              editable={!userInfo.wholeMobile}
              placeholder='请填写手机号'
              value={tel}
              onChangeText={(text) => {
                this.setState({ tel: text });
              }}
            />
          </View>
          <View><Text style={styles.boTip}>请填写您的联系方式，工作人员会尽快与您取得联系！</Text></View>
        </View>

        <View style={styles.submitWrap}>
          <Submit
            disabled={isDisable}
            text='提交'
            boxStyle={{
              width: '90%',
              height: px2dp(80),
              borderRadius: px2dp(10),
            }}
            btnTextStyle={{
              color: '#ffffff'
            }}
            onClick={() => {
              this.handlesubmit();
            }}
          />
        </View>

      </SafeAreaView>
    );
  }

  // 初始化
  init = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { goodsId } = params;
    this.setState({
      goodsId
    }, () => {
      this.getGoodsCarInfo();
    });

    this.getUserInfo();
  };
}
const styles = StyleSheet.create({
  wrap: {
    height: '100%',
    backgroundColor: mainBgColorWhite,
  },
  submitWrap: {
    position: 'absolute',
    bottom: px2dp(100),
    left: '5%',
    backgroundColor: mainBgColorWhite,
    flexDirection: 'row',
    justifyContent: 'center'
  },
  carWrap: {
    backgroundColor: mainBgColorLightGray
  },
  formWrap: {
    backgroundColor: mainBgColorWhite
  },
  formTitle: {
    fontSize: px2dp(18),
    padding: px2dp(30),
    marginTop: px2dp(10),
    color: '#333232'
  },
  boTip: {
    paddingLeft: px2dp(30),
    marginTop: px2dp(10),
    color: '#999896'
  },
  inpWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    borderColor: '#E6E3E1',
    borderBottomWidth: px2dp(1),
    marginBottom: px2dp(20),
    marginLeft: px2dp(30),
    marginRight: px2dp(30)
  },
  mustTip: {
    color: '#EB2F2F'
  },
  inp: {
    flex: 1,
    height: px2dp(45) * 2,
    paddingLeft: px2dp(8) * 2
  },
  itemWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'blue',
    marginTop: px2dp(30),
    marginBottom: px2dp(30),
    padding: px2dp(20),
    backgroundColor: mainBgColorWhite,
    borderRadius: px2dp(10)
  },
  itemRight: {
    marginLeft: px2dp(30)
  },
  itemImg: {
    width: px2dp(200),
    height: px2dp(150),
    borderRadius: px2dp(10)
  },
  itemTitle: {
    fontSize: px2dp(16),
    color: '#333232',
    width: px2dp(480)
  },
  itemParme: {
    fontSize: px2dp(14),
    color: '#999896',
    marginTop: px2dp(4),
    marginBottom: px2dp(14),
    width: px2dp(480)
  },
  priceTitle: {
    fontSize: px2dp(14),
    color: '#666562'
  },
  price: {
    fontSize: px2dp(14),
    color: '#EA0505'
  },
  grayStyle: {
    color: '#CDCCC9'
  }

});
